package com.sleep.psy.external_server.exception;

import com.sleep.psy.external_server.result.Result;
import com.sleep.psy.external_server.result.ResultEnum;
import com.sleep.psy.external_server.result.ResultUtil;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.ArrayList;

/**
 * @author wenliguo
 * @date 2025年04月15日 17:04
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 封装注解返回错误信息
     * @author wenliguo
     * @date 2025/8/12 10:47
     * @param e
     * @return com.sleep.psy.external_server.result.Result
    */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result handleValidationException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        ArrayList<String> arrayList = new ArrayList<>();
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            arrayList.add(fieldError.getDefaultMessage());

        }
        return ResultUtil.error(ResultEnum.PARAMETER_NOT_VALID.getCode(), arrayList.get(0));
    }
}
